package cn.tx.service.impl;

import java.util.Date;
import java.util.Set;

import cn.tx.dao.OrderDetailDao;
import cn.tx.dao.StoreDao;
import cn.tx.dao.StoreDetailDao;
import cn.tx.dao.StoreLogDao;
import cn.tx.model.Emp;
import cn.tx.model.OrderDetail;
import cn.tx.model.OrderModel;
import cn.tx.model.Product;
import cn.tx.model.Store;
import cn.tx.model.StoreDetail;
import cn.tx.model.StoreLog;
import cn.tx.query.StoreQuery;
import cn.tx.service.StoreService;

public class StoreServiceImpl extends BaseServiceImpl<Store, StoreQuery> implements StoreService {

	private StoreDao storeDao;
	
	private StoreDetailDao storeDetailDao;
	
	private StoreLogDao storeLogDao;
	
	private OrderDetailDao orderDetailDao;
	
	
	
	
	
	

	public void setOrderDetailDao(OrderDetailDao orderDetailDao) {
		this.orderDetailDao = orderDetailDao;
	}

	public void setStoreLogDao(StoreLogDao storeLogDao) {
		this.storeLogDao = storeLogDao;
	}

	public void setStoreDetailDao(StoreDetailDao storeDetailDao) {
		this.storeDetailDao = storeDetailDao;
	}

	public void setStoreDao(StoreDao storeDao) {
		this.storeDao = storeDao;
		this.baseDao = storeDao;
	}

	@Override
	public void updateInStock(Emp emp,Integer orderDetailId,Integer productId, Integer inStockNum,
			Integer storeId) {
		//获得当前的仓库
		Store store = storeDao.getObjectById(storeId);
		//获得仓库的明细
		Set<StoreDetail> sdSet = store.getSdSet();
		boolean isExist = false;
		for(StoreDetail sd :sdSet){
			if(sd.getProduct().getProductId().intValue() == productId.intValue()){
				sd.setNum(sd.getNum()+inStockNum);
				isExist = true;
				break;
			}
		}
		if(!isExist){//不存在该商品的明细的时候
			StoreDetail sd = new StoreDetail();
			sd.setNum(inStockNum);
			Store s = new Store();
			s.setStoreId(storeId);
			Product p = new Product();
			p.setProductId(productId);
			
			sd.setStore(s);
			sd.setProduct(p);
			storeDetailDao.save(sd);
		}
		
		StoreLog sl = new StoreLog();
		sl.setEmp(emp);
		OrderDetail od = new OrderDetail();
		od.setOrderDetailId(orderDetailId);
		sl.setOrderDetail(od);
		sl.setStore(store);
		sl.setNum(inStockNum);
		sl.setType(1);
		sl.setOperTime(new Date());
		storeLogDao.save(sl);
		OrderDetail detail = orderDetailDao.getObjectById(orderDetailId);
		detail.setSurplus(detail.getSurplus()-inStockNum);
		OrderModel orderModel = detail.getOrderModel();
		Set<OrderDetail> ods = orderModel.getOds();
		//定义整个订单入库结束标志
		boolean isFinish = true;
		for(OrderDetail od1 : ods){
			if(od1.getSurplus().intValue() != 0){
				isFinish = false;
				break;
			}
		}
		//如果订单没有入库完
		if(!isFinish){
			orderModel.setOrderState(6);
		}else{
			orderModel.setOrderState(7);
		}
		
		
	}
	
	

}
